package com.one.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.one.api.RemoteJudgeService;
import com.one.api.domain.UserExeResult;
import com.one.api.domain.dto.JudgeSubmitDTO;
import com.one.api.domain.vo.UserQuestionResultVO;
import com.one.common.core.constants.CacheConstants;
import com.one.common.core.constants.Constants;
import com.one.common.core.domain.R;
import com.one.common.core.enums.ProgramType;
import com.one.common.core.enums.QuestionResType;
import com.one.common.core.enums.ResultCode;
import com.one.common.core.util.ThreadLocalUtil;
import com.one.common.security.exception.ServiceException;
import com.one.friend.domain.question.Question;
import com.one.friend.domain.question.QuestionCase;
import com.one.friend.domain.question.es.QuestionES;
import com.one.friend.domain.user.UserSubmit;
import com.one.friend.domain.user.dto.UserSubmitDTO;
import com.one.friend.elasticsearch.QuestionRepository;
import com.one.friend.mapper.question.QuestionMapper;
import com.one.friend.mapper.user.UserSubmitMapper;
import com.one.friend.rabbitmq.JudgeProducer;
import com.one.friend.service.user.IUserQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserQuestionService implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private RemoteJudgeService remoteJudgeService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private JudgeProducer judgeProducer;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        //friend模块的判题逻辑
        //先检查提交代码类型
        if(ProgramType.Java.getValue().equals(userSubmitDTO.getProgramType())){
            //执行Java代码逻辑
            //从es中查询题目信息，做好处理生成dto
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);
        }
        //没有支持的语言类型
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        //friend模块的判题逻辑
        //先检查提交代码类型
        if(ProgramType.Java.getValue().equals(userSubmitDTO.getProgramType())){
            //执行Java代码逻辑
            //从es中查询题目信息，做好处理生成dto
            JudgeSubmitDTO judgeSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;
        }
        //没有支持的语言类型
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long questionId, Long examId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        //从数据库中拿取最新提交的数据记录
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId,questionId,examId,currentTime);
        UserQuestionResultVO questionResultVO = new UserQuestionResultVO();
        if (userSubmit == null) {
            questionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        } else {
            questionResultVO.setPass(userSubmit.getPass());
            questionResultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                questionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return questionResultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO submitDTO) {
        Long questionId = submitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if (questionES != null) {
            //从es当中拿数据
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        } else {
            //从数据库当中拿数据，刷新es
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        judgeSubmitDTO.setUserId(userId);
        judgeSubmitDTO.setProgramType(ProgramType.Java.getValue());
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        //拼接主函数
        judgeSubmitDTO.setUserCode(codeContent(submitDTO.getUserCode(),questionES.getMainFunc()));
        //传入用例
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        judgeSubmitDTO.setOutputList(questionCaseList.stream().map(QuestionCase::getOutput).toList());
        judgeSubmitDTO.setInputList(questionCaseList.stream().map(QuestionCase::getInput).toList());
        return judgeSubmitDTO;
    }

    private String codeContent(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            //最后一个字符没有超出长度
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
